const requestUrl = 'http://192.168.110.183:7001'
import { chatbotMessageStore } from '@/stores/chatbotMessage.js'
import { useUserStore } from "@/stores/user.js"

let buffer = ''
/**
 * http请求
 * @param {string} url 请求地址
 * @param {string} method 请求方法
 * @param {any} data 请求参数
 * @param {boolean} enableChunked 是否开启流式返回
 */
export const request = (url, method, data = {}, enableChunked = false) => {
	return new Promise((resolve, reject) => {
		const requestTask = uni.request({
			url: requestUrl + url,
			method,
			data,
			enableChunked,
			success: res => {
				const status = res.statusCode // http状态码
				// 状态码 2xx，参考 axios 的设计
				if (status >= 200 && status < 300) {
					resolve(res.data)
				} else if (status === 401) {
					useUserStore().logout()
					reject(res)
				} else {
					// 其他错误 -> 根据后端错误信息轻提示
					const title = res.data.msg || '出现异常'
					uni.showToast({ icon: 'none', title })
					reject(res)
				}
			},
			fail: err => {
				uni.showToast({ icon: "none", title: "出现异常" })
			}
		})
		// 如果流式返回数据
		requestTask.onChunkReceived(response => {
			const arrayBuffer = response.data
			const arrayBufferss = new Uint8Array(arrayBuffer)
			let str = ''
			for (let i = 0; i < arrayBufferss.length; i++) {
				// unicode字符
				str += String.fromCharCode(arrayBufferss[i])
			}
			// 编码和解码
			buffer += decodeURIComponent(escape(str))
			// 循环检查buffer里面是否包含换行符
			while (buffer.includes('\n')) {
				const index = buffer.indexOf('\n')
				// 留下需要的
				const chunk = buffer.slice(0, index)
				// 去掉已经处理过
				buffer = buffer.slice(index + 1)
				// 判断以data:开头并且不含有data: [DONE]
				if (chunk.startsWith('data: ') && !chunk.includes('[DONE]')) {
					const jsonData = JSON.parse(chunk.replace('data: ', ''))
					chatbotMessageStore().handleText(jsonData)
				}
			}
		})
	})
}

// 请求拦截器
const httpInterceptor = {
	// 请求前触发
	invoke(options) {
		// 添加 token 请求头标识
		const token = useUserStore().userInfo.token
		if (token) {
			options.header = { Authorization: token }
		}
	}
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)